package org.beetl.sql.springboot.conf;

import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.clazz.kit.BeanKit;
import org.beetl.sql.springboot.Routing;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class DynamicRoutingDataSource extends AbstractRoutingDataSource implements Routing {

	protected Map<Object, Object> dsMap = new ConcurrentHashMap<>();
	protected static ThreadLocal<String> dbThreadLocal = ThreadLocal.withInitial(() -> "");


	public DynamicRoutingDataSource() {
		super.setTargetDataSources(new HashMap<>());
	}

	@Override
	protected Object determineCurrentLookupKey() {
		return dbThreadLocal.get();
	}


	@Override
	public void db(String dbName) {
		if (!checkExist(dbName)) {
			throw new IllegalArgumentException("不存在的数据库 "+dbName);
		}
		dbThreadLocal.set(dbName);
	}

	@Override
	public void setTargetDataSources(Map<Object, Object> targetDataSources) {
		super.setTargetDataSources(targetDataSources);
		try {
			Field field = BeanKit.getField(AbstractRoutingDataSource.class, "resolvedDataSources");
			field.setAccessible(true);
			field.set(this, targetDataSources);
			this.dsMap = targetDataSources;
		} catch (Exception exception) {
			throw new UnsupportedOperationException("spring version error for this routing ", exception);
		}
	}

	public Map<Object, Object> getTargetDataSources() {
		return dsMap;
	}

	protected boolean checkExist(String name) {
		boolean exist = dsMap.containsKey(name);
		return exist;

	}


}

